import {
  attrItem,
  attrListType,
  attrValueItem,
  attrValueListType,
  EditableRowProps,
  EditableCellProps,
} from '@/api/product/model/attrTypes';
import { DeleteOutlined } from '@ant-design/icons';
import {
  Button,
  Card,
  Form,
  Input,
  InputRef,
  message,
  Popconfirm,
  Table,
  Tag,
  Tooltip,
} from 'antd';
import { useForm } from 'antd/lib/form/Form';
import type { FormInstance } from 'antd/es/form';
import { ColumnsType } from 'antd/lib/table';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { useImperativeHandle, forwardRef } from 'react';
import { reqAddOrUpdateAttrValue } from '@/api/product/attr';

type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

export const AddOrUpdateAttr = forwardRef((props: any, ref: any) => {
  // 添加或更新平台属性卡片的相关数据和方法
  const [form2] = useForm();
  const [count, setCount] = useState(2);
  const [valueName, setValueName] = useState<string>('');
  // const [id, setId] = useState<number>();
  const [attrId, setAttrId] = useState<number>();
  const [attrName, setAttrName] = useState(''); //属性名
  // const [categoryId, setCategoryId] = useState(-1);
  const [attrValueList, setAttrValueList] = useState<attrValueListType>([
    {
      key: 0,
      id: undefined,
      valueName: '请输入属性值名称',
      attrId: attrId,
    },
  ]); //属性值列表
  // const [attrItem, setAttrItem] = useState<attrValueItem>();
  // const [isShowEdit, setIsShowEdit] = useState(false); //控制是输入属性值还是查看属性值
  // 将方法传递给父组件
  useImperativeHandle(ref, () => ({
    backFill: (row: attrItem) => {
      backFillAttr(row);
    },
  }));

  const backFillAttr = (row: attrItem) => {
    console.log('父组件传入的参数:', row);
  };

  // const [attrList, setAttrList] = useState<attrListType>([]);//属性列表
  // const [attr, setAttr] = useState<attrItem>({
  //   attrName: attrName, // 属性名
  //   attrValueList: attrValueList, // 属性值列表
  //   categoryId: categoryId,
  //   categoryLevel: 3,
  // }); //属性类型

  // const AttrValueColumns: ColumnsType<attrValueItem> = [
  //   // 指定每一行的数据对象的类型
  //   {
  //     title: '序号',
  //     dataIndex: 'id',
  //     render(value, row, index) {
  //       // console.log('render', value, row, index)
  //       return index + 1;
  //     },
  //     fixed: 'left',
  //     width: 100, // 宽度
  //     align: 'center', // 水平居中
  //   },

  //   {
  //     title: '属性值名称',
  //     dataIndex: 'valueName',
  //     key: 'valueName',
  //     render: (data, row, index) => (
  //       <>
  //         {isShowEdit ? (
  //           <Input
  //             style={{ width: 500 }}
  //             value={data}
  //             onChange={(e) => {
  //               console.log(data, 'rdataow');

  //               data = e.target.value;
  //             }}
  //           ></Input>
  //         ) : (
  //           <Tag color="success">{row.valueName}</Tag>
  //         )}
  //       </>
  //     ),
  //     width: 500, // 指定宽度
  //   },

  //   {
  //     title: '操作',
  //     render: (value, row, index) => {
  //       return (
  //         <>
  //           {/* 必须要一个根标签 */}
  //           <Tooltip placement="top" title="删除属性">
  //             <Popconfirm
  //               title={`确定删除${row.valueName}吗?`}
  //               okText="确定"
  //               cancelText="取消"
  //               // onConfirm={() => DelTM(row)}
  //             >
  //               <Button
  //                 type="primary"
  //                 danger
  //                 icon={<DeleteOutlined />}
  //                 className="ml"
  //               />
  //             </Popconfirm>
  //           </Tooltip>
  //         </>
  //       );
  //     },
  //     fixed: 'right', // 固定在右侧
  //     // width: 120, // 指定宽度
  //   },
  // ];

  // 点击取消底部取消按钮
  const cancel = () => {
    props.closeAddCard();
  };

  // 获取属性名
  const getAttrName = (event: any) => {
    // console.log(event.target.value, 'event.target.value');
    setAttrName(event.target.value);
  };
  // 点击保存按钮新增或更新平台属性
  const BottomSave = async () => {
    try {
      //  新增属性
      await reqAddOrUpdateAttrValue({
        attrName: attrName,
        attrValueList: attrValueList, // 属性值列表
        categoryId: props.category3Id,
        categoryLevel: 3,
      });

      // 关闭标签
      props.closeAddCard();
      // 重新获取属性列表
      props.getAttrList();
    } catch (error) {
      message.error('保存失败');
    }

    // console.log(res, 'reqAddOrUpdateAttrValue');
  };

  // 新增属性值
  // const addAttrValue = () => {
  //   setIsShowEdit(true);
  //   attrValueList.push({
  //     valueName: '',
  //   });
  //   const newattrValueList = attrValueList.map((item, index) => {
  //     return item;
  //   });
  //   // console.log(newattrValueList, 'newattrValueList');
  //   setAttrValueList(newattrValueList);
  // };
  const handleAdd = () => {
    const newData: attrValueItem = {
      key: count,
      id: 0,
      valueName: '请输入属性值名称',
      attrId: 3,
    };
    setAttrValueList([...attrValueList, newData]);
    setCount(count + 1);
  };

  // components中的row
  const EditableContext = React.createContext<FormInstance<any> | null>(null);
  const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };

  // components中的cell
  const EditableCell: React.FC<EditableCellProps> = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef<InputRef>(null);
    const form = useContext(EditableContext)!;

    useEffect(() => {
      if (editing) {
        inputRef.current!.focus();
      }
    }, [editing]);

    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    };

    const save = async () => {
      // await form.resetFields()
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({ ...record, ...values });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };

    let childNode = children;

    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{ margin: 0 }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{ paddingRight: 24 }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }

    return <td {...restProps}>{childNode}</td>;
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  //columns设置tabel每行渲染的数据
  const handleDelete = (key: React.Key) => {
    const newData = attrValueList.filter((item) => item.valueName !== key);
    setAttrValueList(newData);
  };
  const handleSave = (row: attrValueItem) => {
    const newData = [...attrValueList];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setAttrValueList(newData);
  };
  const defaultColumns: (ColumnTypes[number] & {
    editable?: boolean;
    dataIndex: string;
  })[] = [
    {
      title: '序号',
      dataIndex: 'id',
      render(value, row, index) {
        // console.log('render', value, row, index)
        return index + 1;
      },
      fixed: 'left',
      width: 100, // 宽度
      align: 'center', // 水平居中
    },

    {
      title: '属性值名称',
      dataIndex: 'valueName',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (data: any, record: any) =>
        attrValueList.length >= 1 ? (
          <Popconfirm
            title="确定删除吗?"
            onConfirm={() => handleDelete(record.key)}
          >
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              className="ml"
            />
          </Popconfirm>
        ) : null,
    },
  ];
  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: attrValueItem) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  // // 获取输入框中输入的属性值
  // const getValueName = (event: any) => {
  //   // console.log(row, 'row');
  //   console.log(event.target.value, 'event');

  //   setValueName(event.target.value);
  // };

  return (
    // 新增或修改属性值卡片
    <Card style={{ margin: 20 }}>
      <Form form={form2} layout="inline">
        <Form.Item name="attrName" style={{ marginBottom: 20 }} label="属性名">
          <Input onChange={getAttrName} value={attrName}></Input>
        </Form.Item>
      </Form>
      <div>
        <Button onClick={handleAdd} type="primary" style={{ marginBottom: 16 }}>
          新增属性值
        </Button>
        <Button type="default" style={{ marginBottom: 16, marginLeft: 10 }}>
          取消
        </Button>
      </div>
      <Table
        components={components}
        rowClassName={() => 'editable-row'}
        bordered
        dataSource={attrValueList}
        columns={columns as ColumnTypes}
        pagination={false}
        style={{ marginBottom: 16 }}
      />
      <div>
        <Button
          type="primary"
          style={{ marginBottom: 10 }}
          onClick={BottomSave}
        >
          保存
        </Button>
        <Button
          type="default"
          style={{ marginBottom: 10, marginLeft: 10 }}
          onClick={cancel}
        >
          取消
        </Button>
      </div>
    </Card>
  );
});
